package com.xky.sportstestdemo01.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xky.sportstestdemo01.common.Result;
import com.xky.sportstestdemo01.pojo.entity.Student;
import com.xky.sportstestdemo01.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 学生信息表(Student)表控制层
 *
 * @author twt
 * @since 2024-11-08 13:50:26
 */
@CrossOrigin
@RestController
@RequestMapping("student")
public class StudentController {

    @Autowired
    StudentService studentService;


    /**
     * 查询全部
     */
    @GetMapping("/selectAll")
    public Result selectAll() {
        List<Student> studentList = studentService.list(new QueryWrapper<Student>().orderByDesc("studentId"));
        return Result.success(studentList);
    }

    /**
     * 新增
     */
    @PostMapping("/add")
    public Result add(@RequestBody Student student) {
        try {
            studentService.save(student);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return Result.error("插入数据库错误");
            } else {
                return Result.error("系统错误");
            }
        }
        return Result.success();
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    public Result update(@RequestBody Student student) {
        studentService.updateById(student);
        return Result.success();
    }

    /**
     * 删除
     */

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        studentService.removeById(id);
        return Result.success();
    }

}


